package com.dreamlin.basepro.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.dreamlin.basepro.App;
import com.dreamlin.network.RetrofitHelper;
import com.google.gson.Gson;

import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class NetHelper {
    private static final MediaType MEDIA_TYPE = MediaType.get("application/json; charset=UTF-8");
    public static boolean isInner = true;
    private static final String BASE_IP = isInner ? "192.168.4.177" : "111.51.65.134";
    //"http://192.168.4.225:62019/api/" "http://111.51.65.134:62019/api/"
    private static final String baseUrl = "http://" + BASE_IP + ":62028/mess/";
    private static final String TOP_URL = "http://" + BASE_IP + ":62019/api/";
    public static final String FILE_URL = "http://" + BASE_IP + ":62026/chat/api/uploadFile";

    private static final Object locker = new Object();
    private static Api api;

    public static String topUrlWrapper(String path) {
        return String.format("%s%s", TOP_URL, path);
    }

    public static Api getApi() {
        if (api == null) {
            synchronized (locker) {
                if (api == null) {
                    api = RetrofitHelper.getInstance()
                            .newRetrofit(baseUrl).create(Api.class);
                }
            }
        }
        return api;
    }

    public static RequestBody convertToBody(Object params) {
        if (params == null)
            throw new NullPointerException("参数为空");
        String toJson = new Gson().toJson(params);
        return RequestBody.create(MEDIA_TYPE, toJson);
    }

    public static boolean getNetStatus() {
        ConnectivityManager cm = (ConnectivityManager) App.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = Objects.requireNonNull(cm).getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

}
